/**
 * 
 * ***/
package Avocado.util{

	import fl.motion.MatrixTransformer;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Matrix;
	import flash.geom.Point;
	
	public class SmartDrag{
		
		private var target:DisplayObject;
		private var isDrag:Boolean = new Boolean(false);
		
		private var startMouseX:Number;
		private var startMouseY:Number;
		private var startRotation:Number;
		
		private var pointsArray:Array;
		
		private var transformMatrix:Matrix;

		public function SmartDrag(_target:DisplayObject){
			target = _target;
			
			if (target.stage){
				addDrag();
			} else {
				waitingForStage();
			}
		}

		/**
		 * 
		 * ***/
		public static function drag(_target:DisplayObject):SmartDrag{
			return new SmartDrag(_target);
		}
		
		

		private function waitingForStage():void{
			target.addEventListener(Event.ADDED_TO_STAGE, targetHasStage);
			function targetHasStage(e:Event):void{
				target.removeEventListener(Event.ADDED_TO_STAGE, targetHasStage);
				addDrag();	
			}
		}
		
		private function addDrag():void{
			pointsArray = new Array;
			
			target.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
			target.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
			
			target.addEventListener(Event.ENTER_FRAME, updateTarget);
		}
		
		private function updateTarget(e:Event):void{
			if (pointsArray.length == 0){
				pointsArray.push(new Point(startMouseX, startMouseY));
			} else {
				if (pointsArray.length < 50) {
					pointsArray.push(new Point(target.stage.mouseX, target.stage.mouseY));
				} else {
					pointsArray.shift();
					pointsArray.push(new Point(target.stage.mouseX, target.stage.mouseY));
				}
			}
			
			// var rotFact:Number = new Number(Math.atan2(target.stage.mouseY-pointsArray[0].y, target.stage.mouseX-pointsArray[0].x)*180/Math.PI);
			var rotFact:Number = new Number(Math.atan2(target.stage.mouseY-target.y, target.stage.mouseX-target.x)*180/Math.PI);
			trace(rotFact);

			if (isDrag == true) {
				target.x = target.stage.mouseX - startMouseX;
				target.y = target.stage.mouseY - startMouseY;
				target.rotation = rotFact;
			}

		}

		private function mouseDown(e:MouseEvent):void{
			target.stage.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
			isDrag = true;
			startMouseX = target.mouseX;
			startMouseY = target.mouseY;
			startRotation = target.rotation;
			trace(e);
		}

		private function mouseUp(e:MouseEvent):void{
			target.stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUp);
			pointsArray = pointsArray.slice(0,0);
			isDrag = false;
			trace(e);
		}

	}
}
